package com.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.dao.CategoryDao;
import com.xiaobaibai.entity.Category;
import com.xiaobaibai.service.ICategoryService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-10-16
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements ICategoryService {


    @Override
    @Cacheable(value = "category",key = "#root.methodName")
    public List<Category> getCategoryList() {
        //汇集所有的分类
        //1.用Map汇集子分类->k:pId v:this
        //2.用List接收母分类
        List<Category> list = this.list();

        List<Category> parentList=new ArrayList<>();
        Map<Integer,List<Category>> map=new HashMap<>();
        list.forEach(c->{
            if(c.getCategoryPId().equals(0))
                parentList.add(c);
            else{
                Integer pId=c.getCategoryPId();
                if(map.containsKey(pId)){
                    //存在就加入
                    map.get(pId).add(c);
                }else{
                    //不存在就创建
                    List<Category> categoryList=new ArrayList<>();
                    categoryList.add(c);
                    map.put(pId,categoryList);
                }
            }
        });

        for (Category category : parentList) {
            category.setChildList(map.get(category.getId()));
        }

        return parentList;
    }
}
